<!--
* @description  : 案件-缴款单文书
* @descriptionDetail: 案件-缴款单文书
* @copyright    : 浙江烟草
* @author       : sy
* @create       : 2022-11-20 14:57:44
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
      <view class="white-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit?'预览':'打印' }}
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="top-title-content">
      <view class="main-title">
        {{ docPayNoteForm.orgShortname }}政府非税收入缴款单
      </view>
    </view>
    <!-- 表单开始 -->
    <view class="content">
      <view style="width: calc(100% + 30px);">
        <form-section title="缴款单信息"></form-section>
      </view>
      <u-form
        label-width="auto"
        :model="docPayNoteForm"
        :label-position="labelPosition"
        :error-type="errorType"
        :rules="rules"
        class="form-content"
        ref="uForm"
      >
        <u-form-item label="缴款二维码" label-position="left">
          <u-icon
            name="grid"
            size="34"
            slot="right"
            :color="payUrl? $theme.u_type_primary: ''"
            @click="payUrl && doPreviewImage()"
          ></u-icon>
        </u-form-item>
        <u-form-item label="行政处罚决定书" right-icon="arrow-right" :label-position="labelPosition" :required="true" prop="fullDocNo" ref="regDocRef">
          <u-select :list="punishList" mode="single-column" v-model="punishShow" @confirm="selectConfirm('decideUuid','fullDocNo',$event)"></u-select>
          <u-input
            :clearable="false"
            :disabled="true"
            placeholder="请选择"
            v-model="docPayNoteForm.fullDocNo"
            @click="()=>{if(state.canEdit) punishShow = true}"
          />
        </u-form-item>
        <u-form-item label="缴款单号" :required="isRequired" :label-position="labelPosition" prop="noticeNo">
          <u-input
            :customStyle="cusStyle"
            @click="openNoticeNo()"
            placeholder="请输入缴款单号"
            :disabled="true"
            v-model="docPayNoteForm.noticeNo"
            maxlength="100"
          />
        </u-form-item>
        <u-form-item label="缴款人" :required="isRequired" :label-position="labelPosition" prop="partyName" ref="partyNameRef">
          <u-input
            placeholder="请输入缴款人"
            :disabled="!state.canEdit"
            v-model="docPayNoteForm.partyName"
            maxlength="100"
          />
        </u-form-item>
        <u-form-item :label="docPayNoteForm.payedResult == '-1'?'缴款状态（当前缴款单未推送，不能在线缴费）':'缴款状态'" :required="isRequired" :label-position="labelPosition">
          <u-input
            placeholder="请输入缴款状态"
            :disabled="true"
            v-model="docPayNoteForm.payedResultName"
            :class="docPayNoteForm.payedResult == '-1' ? 'red':'' "
            maxlength="100"
          />
        </u-form-item>
        <u-form-item label="罚没款（小写）" :required="isRequired" :label-position="labelPosition" prop="payAmt" ref="payAmtRef">
          <u-input
            type="number"
            :disabled="!state.canEdit"
            :clearable="false"
            v-model="docPayNoteForm.payAmt"
            @blur="changeUpperNumber"
          />
        </u-form-item>
        <u-form-item label="罚没款（大写）" :required="isRequired" :label-position="labelPosition" prop="payAmtU">
          <u-input
            :disabled="true"
            v-model="docPayNoteForm.payAmtU"
          />
        </u-form-item>
        <u-form-item label="处罚决定书号" :required="isRequired" :label-position="labelPosition" prop="decideFullNo" ref="decideFullNoRef">
          <u-input
            :disabled="!state.canEdit"
            v-model="docPayNoteForm.decideFullNo"
            placeholder="请输入处罚决定书号"
          />
        </u-form-item>
        <u-form-item label="罚没案由" :label-position="labelPosition">
          <u-input type="textarea" placeholder="请输入罚没案由" :disabled="true" v-model="docPayNoteForm.caseProp" />
        </u-form-item>
        <u-form-item label="缴款方式（任选其一）" :label-position="labelPosition">
          <u-row>
            <u-col span="12">
              1、支付宝扫描下方二维码进行缴款；
            </u-col>
            <u-col span="12">
              2、微信扫描下方二维码进行缴款；
            </u-col>
            <u-col span="12">
              3、皖事通APP扫描下方二维码进行缴款。
            </u-col>
            <u-col span="12">
              注：成功办理缴费后，已开通财政电子票据的单位可凭20位缴款识别码到安徽财政电子查验平台获取电子票据（http://czpj.ahzwfw.gov.cn:8888/）。
            </u-col>
          </u-row>
        </u-form-item>
        <u-form-item label="所属单位" :label-position="labelPosition">
          <u-input
            :disabled="true"
            v-model="docPayNoteForm.orgShortname"
          />
        </u-form-item>
        <u-form-item
          label="文书日期"
          label-width="200"
          right-icon="arrow-right"
          :required="true"
          ref="docDateChangeRef"
        >
          <u-input
            :disabled="true"
            placeholder="请选择日期"
            v-model="docPayNoteForm.docDate"
            @click="()=>{state.canEdit&&(isShowDocDate = true)}"
          />
        </u-form-item>
        <view style="margin: 0px -16px;">
          <u-gap :height="$theme.cm_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
        </view>
        <view style="width: calc(100% + 30px);">
          <form-section title="执行项目信息"></form-section>
        </view>
        <u-form-item :border-bottom="false">
          <view class="" style="width: 100%;">
            <view class="u-p-b-15">
              <u-table font-size="26">
                <u-tr class="u-tr">
                  <u-th width="20%" class="u-th">
                    项目编码
                  </u-th>
                  <u-th class="u-th" width="32%">
                    项目名称
                  </u-th>
                  <u-th class="u-th">
                    数量
                  </u-th>
                  <u-th class="u-th">
                    标准
                  </u-th>
                  <u-th class="u-th">
                    金额
                  </u-th>
                </u-tr>
                <u-tr class="u-tr" v-for="item in dataList" :key="item.proCode">
                  <u-td width="20%" class="u-td">
                    {{ item.proCode }}
                  </u-td>
                  <u-td class="u-td" width="32%">
                    {{ item.proName }}
                  </u-td>
                  <u-td class="u-td">
                    {{ item.qty }}
                  </u-td>
                  <u-td class="u-td">
                    {{ item.payAmt }}
                  </u-td>
                  <u-td class="u-td">
                    {{ item.payAmt }}
                  </u-td>
                </u-tr>
              </u-table>
            </view>
          </view>
        </u-form-item>
        <view style="margin: 0px -16px;">
          <u-gap :height="$theme.cm_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
        </view>
        <view style="width: calc(100% + 30px);">
          <form-section title="二维码信息"></form-section>
        </view>
        <u-form-item :label-position="labelPosition">
          <image
            class="m-preview-image"
            :src="payUrl"
            :mode="imageMode"
            @tap.stop="doPreviewImage"
          ></image>
        </u-form-item>
        <!-- 表单结束 -->
      </u-form>
    </view>
    <!-- 底部按钮开始 -->
    <view class="submit-btns btn-other-cls" v-if="state.canEdit">
      <u-button plain class="u-btn" type="primary" @click="submitBtn('save')">
        保存
      </u-button>
      <u-button class="u-btn" type="primary" @click="submitBtn('submit')">
        提交
      </u-button>
    </view>
    <!-- 底部按钮结束 -->
    <!-- 日期控件 -->
    <u-calendar mode="date" :max-date="yestDate" v-model="isShowDocDate" @change="changeDate('docDate',$event)">
    </u-calendar>
  </view>
</template>

<script>
	import caseCommon from "../caseCommonMixin.js";
	import caseService from '@/service/case/case.service.js';
	import officeService from "@/service/case/office.service.js";
	import FormSection from "@/components/form-section.vue";
	import {
		PATHROOT,
	} from '@/common/path.config';
	import {
		dateUtils,
		getUpper,
	} from "@/common/util";
	import fabButton from '@/components/uni-fab.vue';
  import commonService from "@/service/common/common.service";

	export default {
		components: {
			FormSection,
			fabButton
		},
		mixins: [caseCommon, ],
		data() {
			return {
				errorType: ['border-bottom', 'message', ],
				isRequired: true, // 是否显示必填项
				labelPosition: 'top',
				docPayNoteForm: {},
				caseParam: {}, // 上个页面传过来的参数
				rules: {
					fullDocNo: [{
						required: true,
						message: '请选择行政处罚决定书',
						trigger: ['change', 'blur', ],
					}, ],
					partyName: [{
						required: true,
						message: '请输入缴款人',
						trigger: ['change', 'blur', ],
					}, ],
					payAmt: [{
						validator: (rule, value, callback) => {
							return !this.$u.test.isEmpty(value);
						},
						message: '请输入罚没款（小写）',
						trigger: ['change', 'blur', ],
					}, ],
					decideFullNo: [{
						required: true,
						message: '请输入处罚决定书号',
						trigger: ['change', 'blur', ],
					}, ],
				},
				doc: {},
				isShowDocDate: false,
				yestDate: this.$u.timeFormat(Date.now()),
				punishList: [],
				punishDecideList: [],
				punishShow: false,
				payedResult: '',
				payedResultMap: {
					'-1': '待推送',
					0: '待缴款',
					1: '已缴费',
				},
				dataList: [],
				payUrl: '',
				user: this.$store.state.userInfo,
				imageMode: "aspectFill",
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}],
        paymentRestUrl: '',
        cusStyle: {
          color: '#1589ee',
        },
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad() {
			this.caseParam = this.getRouteParam();
			console.log('参数：' + JSON.stringify(this.caseParam));
      commonService.getSysConfig("pricing_confirm_config", "pricing_result_url").then((d) => {
        if (d.success) {
          this.paymentRestUrl = d.msg;
        }
      });
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo;
				this.setRightBtns();
			});
			this.initDocData();
			this.initDecideList();
		},
		methods: {
			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			// 打印/预览
			printOrDown(flag) {
				// 点击提交、保存按钮
				let saveFlag = this.validForm('save');
				if(saveFlag){
				  if(this.payedResult == '-1'){
					this.$u.toast("当前缴款单未推送，不能在线缴费");
					return false;
				  }
				  if (flag) {
					// 调接口预览
					this.submitDocInfo('preview');
				  } else {
					this.downloadFile(this.doc.pdfFileId);
				  }
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast("没有文书");
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			// 初始化文书
			initDocData() {
				let parms = {
					id: this.caseParam.id,
					docUuid: this.caseParam.docUuid,
					bizUuid: this.caseParam.bizUuid,
				}
				this.$u.loading('加载中...');
				officeService.docFields(this.caseParam.docUuid, true).then(docConfigs => {
					if (docConfigs.success) {
						this.docFields = [...docConfigs.data, ];
						officeService.getDocPaymentNote(parms).then((res) => {
							this.$u.hideLoading();
							let [tiInfo, rs, ] = [{}, {}, ];
							if (res.success && res.data.length === 2) {
								tiInfo = res.data[0];
								rs = res.data[1];
								Object.keys(tiInfo).forEach(key => {
									rs[key] = tiInfo[key];
								});
							} else {
								rs = res.data[0];
							}
							this.docPayNoteForm = rs;
							this.docPayNoteForm.fullDocNo = rs.decideFullNo;
							if (this.docPayNoteForm.paymentNoteUuid) {
								this.payUrl = PATHROOT.CASE + '/decide/doc-payment-note/getPaymentQrCode.do?paymentNoteUuid=' + this.docPayNoteForm.paymentNoteUuid + '&tk=' + this.user.tk;
								this.dataList = [{
									proCode: this.docPayNoteForm.projectCode,
									proName: '罚没收入',
									qty: 1,
									payAmt: this.docPayNoteForm.payAmt,
								}, ];
							}
							this.setPayedResult();
							this.changeUpperNumber();
						}).catch(er => {
							console.log(er);
							this.$u.hideLoading();
							this.$u.toast(er);
						});
					} else {
						this.$u.toast(docConfigs.msg);
					}
				}).catch(er => {
					console.log(er);
					this.$u.hideLoading();
					this.$u.toast(er);
				});
			},
			// 初始化行政处罚决定书
			initDecideList() {
				this.punishList = [];
				officeService.getPunishDecideListByCaseUuid(this.caseParam.caseUuid).then((res) => {
					if (res.success) {
						this.punishDecideList = res.data ? res.data : [];
						this.punishDecideList.forEach((item) => {
							this.punishList.push({
								value: item.decideUuid,
								label: item.fullDocNo,
							});
						});
					}
				}).catch((err) => {
					this.$u.toast(err);
				});
			},
			// 转换大写
			changeUpperNumber() {
				this.docPayNoteForm.payAmt && this.$set(this.docPayNoteForm, 'payAmtU', getUpper(this.docPayNoteForm.payAmt));
			},
			changeDate(type, e) {
				this.docPayNoteForm[type] = dateUtils.dateFormat("yyyy年MM月dd日", new Date(e.result));
				this.$refs.docDateChangeRef.validation();
			},
			// 下拉框选择
			selectConfirm(type, name, e) {
				this.docPayNoteForm[name] = '';
				this.docPayNoteForm[type] = '';
				let noticeNo = '';
				e.map((val, index) => {
					this.docPayNoteForm[type] = val.value;
					this.docPayNoteForm[name] = val.label;
				});
				this.$refs.regDocRef.validation();
				let chooseData = this.punishDecideList.filter((item) => {
					if (item.decideUuid == this.docPayNoteForm.decideUuid) return item;
				});
				if (chooseData.length > 0) {
					this.objMerge(this.docPayNoteForm, chooseData[0]);
					this.docPayNoteForm.payAmt = chooseData[0].confiscateAmt + '';
					this.docPayNoteForm.decideFullNo = chooseData[0].fullDocNo;

					console.log(this.docPayNoteForm);
					noticeNo = chooseData[0].noticeNo;
				}
				this.setPayedResult();
				this.getNoticeNoData(noticeNo);
				this.changeUpperNumber();
				this.dataList = [{
					proCode: this.docPayNoteForm.projectCode,
					proName: '罚没收入',
					qty: 1,
					payAmt: this.docPayNoteForm.payAmt || '0',
				}, ];
				this.$refs.payAmtRef.validation();
				this.$refs.partyNameRef.validation();
				this.$refs.decideFullNoRef.validation();
			},
			// 获取缴款单号
			getNoticeNoData(noticeNo) {
				officeService.getNoticeNo({
					noticeNo: noticeNo,
				}).then((res) => {
					if (res.success) {
						this.docPayNoteForm.noticeNo = res.msg;
					}
				});
			},
			setPayedResult() {
				this.payedResult = this.docPayNoteForm.payedResult;
				this.docPayNoteForm.payedResultName = this.payedResultMap[this.docPayNoteForm.payedResult] || '';
			},
			doPreviewImage() {
				this.$deviceApi.previewImage([this.payUrl, ], this.payUrl);
			},
			// 表单验证
			validForm(type) {
				let basicValid = false;
				this.btnType = type;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						basicValid = true;
						console.log('表单验证通过');
					} else {
						basicValid = false;
						console.log('表单验证失败');
					}
				});
				return basicValid;
			},
			submitBtn(type) {
				// 点击提交、保存按钮
				let flag = this.validForm(type);
				if (flag) {
					if(this.payedResult == '-1'){
						this.$u.toast("当前缴款单未推送，不能在线缴费");
						return false;
					}
					if (type == 'submit') {
						this.$modal.confirm("完成后不可修改，请确认是否填写完整准确无误？", () => {
							this.submitDocInfo(type);
						});
					} else {
						this.submitDocInfo(type);
					}
				}
			},
			submitDocInfo(type) {
				// 保存/提交
				let {
					id,
					docUuid,
					titemUuid,
				} = this.caseParam;
				this.docPayNoteForm.caseUuid = this.caseParam.caseUuid;
				this.$u.loading('数据保存中...');
				officeService.saveDocPaymentNote(this.docPayNoteForm, docUuid, titemUuid, id, this.caseParam.type).then(
					res => {
						this.$u.hideLoading();
						if (res.success) {
							this.objMerge(this.docPayNoteForm, res.bean);
							try {
								if (!this.doc) this.doc = res.data[0];
							} catch (e) {
								console.log(e);
							}
							this.payUrl = PATHROOT.CASE + '/decide/doc-payment-note/getPaymentQrCode.do?paymentNoteUuid=' + this.docPayNoteForm.paymentNoteUuid + '&tk=' + this.user.tk;
							if (type == 'submit') {
								this.$u.loading('数据提交中...');
								officeService.submitDocPaymentNote(this.docPayNoteForm, docUuid, titemUuid, id, this
									.caseParam.type).then(res => {
									this.$u.hideLoading();
									this.$u.toast(res.msg);

									if (res.success) {
										this.backPrev({
											paramKey: "offiList",
											param: {
												caseUuid: this.caseParam.bizUuid,
												caseCode: this.caseParam.caseCode,
												caseType: this.caseParam.caseType,
											},
										});
									}
								})

							} else if (type == 'preview') {
								this.$u.loading('生成PDF中...');
								officeService.buildLocalPunish("/decide/doc-payment-note", this.doc.docInsUuid).then(
									pdfId => {
										this.$u.hideLoading();
										if (pdfId.success) {
											this.downloadFile(pdfId.bean, "预览", false);
										} else {
											this.$u.toast(pdfId.msg);
										}
									});
							} else {
								this.$u.toast(res.msg);
							}
						} else {
							this.$u.hideLoading();
							this.$u.toast(res.msg);
						}
					})
			},
      openNoticeNo(){
        if (this.docPayNoteForm.noticeNo === undefined || this.docPayNoteForm.noticeNo === ''){
          this.$u.toast('缴款单号为空，请选择行政处罚决定书后重新点击！');
          return;
        }
        if(this.payedResult != '1'){
          this.$u.toast('当前缴款单未缴费，无法访问缴费单地址！');
          return false;
        }
        // 判断是否获取到url
        if (this.paymentRestUrl === undefined || this.paymentRestUrl === ''){
          this.$u.toast('请配置缴费单访问地址后重新点击！');
          return;
        }
        let url =  this.paymentRestUrl + this.docPayNoteForm.noticeNo;
        this.openURL(url);
      },
      openURL(href) {
        // #ifdef APP-PLUS
        plus.runtime.openURL(href)
        // #endif
        // #ifdef H5
        window.open(href)
        // #endif
        // #ifdef MP
        uni.setClipboardData({
          data: href,
          success() {
            uni.showToast({
              title: '网址已复制，请在手机浏览器里粘贴该网址',
              icon: 'none'
            })
          }
        })
        // #endif
      },
		},
	}
</script>

<style lang="scss" scoped>
	@import "../case_common.scss";

	.page {
		padding: 0;
	}

	.content {
		padding: 0 $cm-content-paddng-row 80px;
	}

	.red {
		color: $u_type_error;
	}

	.m-preview-image {
		display: block;
		width: 100px;
		height: 100px;
		border-radius: 10rpx;
	}
</style>
